package baibeiwallet;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.LogUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.web3j.crypto.CipherException;
import org.web3j.crypto.Keys;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import baibeiwallet.activity.CreateWalletActivity1;
import baibeiwallet.activity.InprotWalletActivity1;
import baibeiwallet.activity.WalletDetailActivity1;
import baibeiwallet.event.CreateWalletEvent;
import baibeiwallet.event.SelWalletEvent;
import baibeiwallet.model.ETHWallet3;
import baibeiwallet.model.TokenModel;
import baibeiwallet.solidity.Token;
import baibeiwallet.utils.BaiBeiWalletUtils;
import baibeiwallet.utils.BaibeiTransferUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;

public class WalletManagerActivity1 extends BaseActivity {
    @BindView(R.id.leftItem)
    ImageView leftItem;
    @BindView(R.id.rv)
    RecyclerView mRecyclerView;
    WalletAdapter mAdapter;
    List<BaibeiWallet> mDatas = new ArrayList<>();
    @BindView(R.id.nodatashow_body)
    RelativeLayout nodatashowBody;
    List<ETHWallet3> ethWallets = new ArrayList<>();

    @Override
    protected MyPreenter initPreenter() {
        return null;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_wallet_manager3;
    }

    @Override
    protected void initVariables() {
        new ActionBarHelper(this).setTitle(getString(R.string.title_hint_item20));
    }

    @Override
    protected void initViews() {
        nodatashowBody.setVisibility(View.VISIBLE);
        mRecyclerView.setVisibility(View.GONE);
        init();
    }

    private void init() {
        mAdapter = new WalletAdapter();

        LinearLayoutManager llm = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(llm);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    protected void loadData() {
//        if (WalletManager.getInstance().getWalletAll() == null || WalletManager.getInstance().getWalletAll().size() == 0) {
        showWaitDialog();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        LogUtil.d("load1");
        ethWallets = WalletDaoUtils.loadAll();
        new Thread(new Runnable() {
            @Override
            public void run() {
                LogUtil.d("load2");
//               showWaitDialog();
                mDatas = WalletManager.getInstance().getWalletAll();
                if (ethWallets != null) {
                    LogUtil.d("load3");
                    for (ETHWallet3 ethWallet : ethWallets) {
                        boolean ss = true;
                        for (BaibeiWallet baibeiWallet1 : mDatas) {
                            if (Keys.toChecksumAddress(baibeiWallet1.getWalletFile().getAddress()).equalsIgnoreCase(ethWallet.getAddress())) {
                                ss = false;

                                break;
                            }
                        }

                        if (ss) {
                            BaibeiWallet baibeiWallet = null;
                            try {
                                if (!TextUtils.isEmpty(ethWallet.getKeystorePath()) && !TextUtils.isEmpty(ethWallet.getPassword())) {
                                    baibeiWallet = BaiBeiWalletUtils.loadByKeyStore(ethWallet.getPassword(), ethWallet.getKeystorePath());
                                } else if (!TextUtils.isEmpty(ethWallet.getMnemonic()) && !TextUtils.isEmpty(ethWallet.getPassword())) {
                                    baibeiWallet = BaiBeiWalletUtils.generateBip44Wallet(ethWallet.getMnemonic(), ethWallet.getPassword());
                                }
                            } catch (CipherException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                            // BaibeiWallet baibeiWallet = BaiBeiWalletUtils.generateBip44Wallet(mnemonic, pwd);
                            // WalletManager.getInstance().addWallet(baibeiWallet);
                            if (baibeiWallet != null) {
                                baibeiWallet.setPassword(ethWallet.getPassword());
                                baibeiWallet.setWalletName(ethWallet.getName());
                                WalletManager.getInstance().addWallet(baibeiWallet, false);
                            }
                        }
                    }
                    LogUtil.d("load4");
//                   if (ethWallets.size() != 0) {
//                       nodatashowBody.setVisibility(View.GONE);
//                       mRecyclerView.setVisibility(View.VISIBLE);
//                   } else {
//                       nodatashowBody.setVisibility(View.VISIBLE);
//                       mRecyclerView.setVisibility(View.GONE);
//                   }

                }
//                mAdapter.setData();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                EventBus.getDefault().post(new CreateWalletEvent(-1));
                LogUtil.d("load5");

//               hideWaitDialog();
            }
        }).start();

        if (ethWallets == null || ethWallets.size() == 0) {
            LogUtil.d("load6");
            hideWaitDialog();
        }
        LogUtil.d("load7");

        getGasForETH();//获取gasprice
//        }

    }

    private void getGasForETH() {
        BaibeiTransferUtils.getGasForETH()
                .subscribe(mGasObserver);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @OnClick(R.id.btn_create_wallet)
    public void onClickCreateWallet() {
        if (mDatas != null && mDatas.size() == 10) {
            showToast(getString(R.string.wallet_hint_warn4));
            return;
        }

        Intent i = new Intent(WalletManagerActivity1.this, CreateWalletActivity1.class);
        startActivity(i);
    }

    @OnClick(R.id.btn_inport_wallet)
    public void onClickInportWallet() {
        Intent i = new Intent(WalletManagerActivity1.this, InprotWalletActivity1.class);
        startActivity(i);
    }


    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    public class WalletHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_title)
        public TextView mTvTitle;
        @BindView(R.id.tv_address)
        public TextView mTvAddress;
        @BindView(R.id.btn_copy_address)
        public TextView mBtnCopy;
        @BindView(R.id.btn_sel)
        public TextView mBtnSel;
        @BindView(R.id.ly_body)
        public LinearLayout lybody;
        @BindView(R.id.tv_money)
        public TextView mMoney;


        public WalletHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    TokenModel token, token1;

    public class WalletAdapter extends RecyclerView.Adapter<WalletHolder> {

        List<BaibeiWallet> mDatas;
        ETHWallet3 ethWallet;
        boolean refresh;
        BaibeiWallet refreshWallet;

        public WalletAdapter() {
            ethWallet = WalletDaoUtils.getCurrent();
            mDatas = WalletManager.getInstance().getWalletAll();
        }

        public void setData() {
            mDatas = WalletManager.getInstance().getWalletAll();
            ethWallet = WalletDaoUtils.getCurrent();
            if (mDatas != null && mDatas.size() != 0) {
                if (nodatashowBody != null)
                    nodatashowBody.setVisibility(View.GONE);
                if (mRecyclerView != null)
                    mRecyclerView.setVisibility(View.VISIBLE);

                refreshWallet = mDatas.get(0);
                refreshPricedata(mDatas, 0);
            }
            hideWaitDialog();
            notifyDataSetChanged();
        }

        public void setData(int ss) {
            mDatas = WalletManager.getInstance().getWalletAll();
            ethWallet = WalletDaoUtils.getCurrent();
            if (mDatas != null && mDatas.size() != 0) {
                if (nodatashowBody != null)
                    nodatashowBody.setVisibility(View.GONE);
                if (mRecyclerView != null)
                    mRecyclerView.setVisibility(View.VISIBLE);
            }
            hideWaitDialog();
            notifyDataSetChanged();
        }


        public void setData(boolean refresh) {
            this.refresh = refresh;
            LogUtil.d("load12");
            mDatas = WalletManager.getInstance().getWalletAll();
            ethWallet = WalletDaoUtils.getCurrent();
            if (mDatas != null && mDatas.size() != 0) {
                if (nodatashowBody != null)
                    nodatashowBody.setVisibility(View.GONE);
                if (mRecyclerView != null)
                    mRecyclerView.setVisibility(View.VISIBLE);
                refreshWallet = mDatas.get(0);
                refreshPricedata(mDatas, 0);
            }
            LogUtil.d("load13");
            hideWaitDialog();
            notifyDataSetChanged();
            LogUtil.d("load14");

        }

        private void refreshPricedata(List<BaibeiWallet> mDatas, int indext) {
            refreshWallet = mDatas.get(indext);
            token = new TokenModel("", "ETH", true);
            token1 = new TokenModel(Constant.G12ContractAddress, Constant.G12ContractName, false);
            getBalanceForETH(Keys.toChecksumAddress(refreshWallet.getWalletFile().getAddress()));
        }


        private void refreshtokenPricedata(List<BaibeiWallet> mDatas, int indext) {
            refreshWallet = mDatas.get(indext);
            token = new TokenModel("", "ETH", true);
            token1 = new TokenModel(Constant.G12ContractAddress, Constant.G12ContractName, false);
            loadContract(refreshWallet);
        }

        public List<BaibeiWallet> getData() {
            return mDatas;
        }

        @NonNull
        @Override
        public WalletHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = View.inflate(parent.getContext(), R.layout.item_wallet3, null);
            return new WalletHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull WalletHolder holder, int position) {
            DecimalFormat dec = new DecimalFormat("0.0000");
//            holder.mMoney.setText("$ "+dec.format(mDatas.get(position).getMoney())+"");
            String money2 = walletMoneyMap.get(mDatas.get(position).walletFile.getAddress());
            holder.mMoney.setText("$ " + dec.format(Double.parseDouble(TextUtils.isEmpty(money2) ? "0" : money2)) + "");

            holder.mTvTitle.setText(mDatas.get(position).getWalletName());
            String adress = Keys.toChecksumAddress(mDatas.get(position).walletFile.getAddress());


            holder.mTvAddress.setText(adress.length() >= 40 ? adress.substring(0, 9)
                    + "...." + adress.substring(adress.length() - 11, adress.length()) : adress);

//            holder.mTvAddress.setText(adress);
            holder.mBtnCopy.setOnClickListener((view) -> {
                ClipboardUtils.copy(holder.mTvAddress.getText().toString());
                Log.i("TAG", "onBindViewHolder: 复制地址 " + holder.mTvAddress.getText().toString());
            });

            if (ethWallet != null &&
                    ethWallet.getAddress().equalsIgnoreCase(Keys.toChecksumAddress(mDatas.get(position).getWalletFile().getAddress()))) {
//                holder.mBtnSel.setText("已选中");
                holder.mBtnSel.setVisibility(View.VISIBLE);
                holder.lybody.setBackgroundDrawable(getResources().getDrawable(R.drawable.jieidanwallet_item_bg1));
                holder.mBtnSel.setBackgroundDrawable(getResources().getDrawable(R.drawable.check_box_jieidan));
                holder.mBtnSel.setOnClickListener(null);

                if (refresh) {
                    refresh = false;
                    EventBus.getDefault().post(new SelWalletEvent(position));
                }

            } else {
//                holder.mBtnSel.setText("选中");
                holder.mBtnSel.setVisibility(View.GONE);
                holder.lybody.setBackgroundDrawable(getResources().getDrawable(R.drawable.vip_bg1));
//                holder.mBtnSel.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_btn_bg));
                holder.mBtnSel.setOnClickListener((view) -> {
//                WalletDaoUtils.
                    EventBus.getDefault().post(new SelWalletEvent(position));
//                    Toast.makeText(MyApp.sInstance, "已选中", Toast.LENGTH_SHORT).show();
                    setData();
                });
            }
            holder.lybody.setOnClickListener((view) -> {
//                WalletDaoUtils.
//                showToast("点击 item" + position);

                if (mDatas.get(position) == null) {
                    showToast(getString(R.string.profile_hint_item6));
                    return;
                }
                Intent i = new Intent(WalletManagerActivity1.this, WalletDetailActivity1.class);
                i.putExtra("index", position);
                startActivity(i);

            });
//            holder.mTvAddress.setOnClickListener((view) -> {
//
//            });

        }

        @Override
        public int getItemCount() {
            return mDatas.size();
        }


        private void getBalanceForETH(String addr) {
            BaibeiTransferUtils.getBalanceForETH(addr)
                    .subscribe(mEthBalanceObserver);
        }


        private void loadContract(BaibeiWallet mWallet) {
            if (token1 != null && token1.isEth) {
                //以太坊不需要加载合约
                return;
            }

            BaibeiTransferUtils.loadContract(mWallet, token1.getAddr(), getGasPrice(), getGasLimit())
                    .subscribe(new SingleObserver<Token>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                        }

                        @Override
                        public void onSuccess(Token token) {
//                        Toast.makeText(TransferActivity1.this, "合约加载完成！", Toast.LENGTH_SHORT).show();
                            if (token == null) {
//                                showToast("合约未加载完成");
                                showToast(getString(R.string.common_loaderrritry));

                                return;
                            }

                            BaibeiTransferUtils.balanceOf(token, mWallet.getWalletFile().getAddress())
                                    .subscribe(mBalanceObserver);
                        }

                        @Override
                        public void onError(Throwable e) {
//                            showToast("合约加载失败!");
                            showToast(getString(R.string.common_loaderrritry));
//                        Toast.makeText(TransferActivity1.this, "合约加载失败！", Toast.LENGTH_SHORT).show();
                        }
                    });
        }

        Map<String, String> walletMoneyMap = new HashMap<>();
        private SingleObserver<BigInteger> mEthBalanceObserver = new SingleObserver<BigInteger>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onSuccess(BigInteger bigInteger) {
                BigDecimal bigDecimal = new BigDecimal(bigInteger + ".0000");
                BigDecimal bigDecimal1 = new BigDecimal("1000000000000000000.0000");
                List<BaibeiWallet> mDatas = WalletManager.getInstance().getWalletAll();
                for (int i = 0; i < mDatas.size(); i++) {
                    if (mDatas.get(i).getWalletFile().getAddress().equalsIgnoreCase(refreshWallet.getWalletFile().getAddress())) {
                        if (MyApp.wallets.size() != 0) {

                            walletMoneyMap.put(refreshWallet.getWalletFile().getAddress(),
                                    Double.parseDouble(bigDecimal.divide(bigDecimal1, BigDecimal.ROUND_HALF_UP).toString()) * MyApp.wallets.get(0).getPrice() + "");

//                            BaibeiWallet baibeiWallet = WalletManager.getInstance().getWalletAll().get(i);
//                            baibeiWallet.setMoney(Double.parseDouble(bigDecimal.divide(bigDecimal1, BigDecimal.ROUND_HALF_UP).toString()) * MyApp.wallets.get(0).getPrice());
//                            WalletManager.getInstance().update(i, baibeiWallet);

                            if (i + 1 < mDatas.size()) {
                                refreshPricedata(mDatas, i + 1);
                            } else {//加载代币
                                refreshtokenPricedata(mDatas, 0);
                            }
                            setData(1);
                        }
                        break;
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
            }
        };

        private SingleObserver<BigInteger> mBalanceObserver = new SingleObserver<BigInteger>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onSuccess(BigInteger bigInteger) {
                List<BaibeiWallet> mDatas = WalletManager.getInstance().getWalletAll();
                for (int i = 0; i < mDatas.size(); i++) {
                    if (mDatas.get(i).getWalletFile().getAddress().equalsIgnoreCase(refreshWallet.getWalletFile().getAddress())) {
                        if (MyApp.wallets.size() != 0) {


                            String money1 = walletMoneyMap.get(refreshWallet.getWalletFile().getAddress());
                            walletMoneyMap.put(refreshWallet.getWalletFile().getAddress(),
                                    Double.parseDouble(TextUtils.isEmpty(money1) ? "0" : money1) + Double.parseDouble(bigInteger.toString()) * Constant.G12ContractPrice + "");

//                            BaibeiWallet baibeiWallet = WalletManager.getInstance().getWalletAll().get(i);
//                            baibeiWallet.setMoney(mDatas.get(i).getMoney() + Double.parseDouble(bigInteger.toString()) * MyApp.wallets.get(1).getPrice());
//                            WalletManager.getInstance().update(i, baibeiWallet);

                            if (i + 1 < mDatas.size()) {//加载代币
                                refreshtokenPricedata(mDatas, i + 1);
                            }
                            setData(1);
                        }
                        break;
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
            }
        };

        private BigInteger getGasPrice() {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                Request<?, EthGasPrice> ethGasPriceRequest = Web3jUtils.initWeb3j(null).ethGasPrice();
//                BigInteger gasPrice = null;
//                try {
//
//                    EthGasPrice send = ethGasPriceRequest.send();
//                    gasPrice = send.getGasPrice();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                Log.e("9998",gasPrice.toString());
//            }
//        }).start();


//        return gasebigInteger!=null?gasebigInteger:new BigInteger("100000000000");

            return gasebigInteger;
        }

        private BigInteger getGasLimit() {
            return BigInteger.valueOf(600000);
        }


    }

    private BigInteger gasebigInteger = new BigInteger("100000000000");

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCreateWalletEvent(CreateWalletEvent cwe) {
        LogUtil.d("load9");
        if (cwe.index == -1) {//本页面刷新
            LogUtil.d("load10");
            mAdapter.setData(false);
        } else {
            LogUtil.d("load11");
            mAdapter.setData(true);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSelWalletEvent(SelWalletEvent sel) {
        if (sel.sellectwallet != null && sel.sellectwallet.indexOf("sellectwallet") != -1) {
            mAdapter.setData(false);
        }
    }

    private SingleObserver<BigInteger> mGasObserver = new SingleObserver<BigInteger>() {
        @Override
        public void onSubscribe(Disposable d) {
        }

        @Override
        public void onSuccess(BigInteger bigInteger) {
            LogUtil.d("gas=" + bigInteger.toString());
            gasebigInteger = bigInteger;
//            BigDecimal bigDecimal = new BigDecimal(gasebigInteger.multiply(getGasLimit()) + ".00000");//gaseprice*gaselimit
//            BigDecimal bigDecimal1 = new BigDecimal("1000000000000000000.00000");
        }

        @Override
        public void onError(Throwable e) {

        }
    };
}
